import { memo, useEffect, useState } from "react";
import { Position, useReactFlow, Node } from "@xyflow/react";
import { Card, Modal } from "antd";
import useSelectBorder from "../../store/useSceneData";
import CustomHandle from "../CustomHandle";
import NodeOperation from "../../components/NodeOperation";
import VariableConfig from "../../components/VariableConfig";
import useVariable from "../../store/useVariable";
import Subtitle from "@/components/Subtitle";

/**
 * 提示词模版
 * @param param0
 * @returns
 */
function InputNode({ id, data }: Node) {
  const { select, setSelectId, debug } = useSelectBorder()
  const { setNodes, setCenter } = useReactFlow();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const { variable, setVariable } = useVariable();

  const handleFocus = () => {
    setSelectId(id);
  };

  useEffect(() => {
    console.log("data.variable", data.variable)
    if (data.variable) {
      setTimeout(() => {
        setVariable(data.variable as Variable[])
      }, 0)
    }
  }, [])

  useEffect(() => {
    if (select[id] && debug) {
      setNodes((nodes: Node[]) => {
        const node = nodes.find(node => node.id == id)
        setCenter(node.position.x + 200, node.position.y, { zoom: 1, duration: 500 })
        return [...nodes];
      })
    }
  }, [select[id]])


  return (
    <NodeOperation nodeId={id} onClick={() => setIsModalOpen(true)}>
      <Card
        title={<div className='flex'>
          <Subtitle imgUrl='img/input.png' title={data.title as string || '开始'} id={id} />
        </div>}
        style={{
          outline: select[id] ? "2px solid #145FF0" : "none",
          width: 304,
        }}
        onClick={handleFocus}
        tabIndex={0}
      >
        {variable.filter(v => v.value != "sys.query" && v.value != "sys.result"
          && v.value.startsWith("sys.")).map(v =>
            <div
              className="bg-[#F3F4F7] mb-1 rounded-lg text-[#667085] flex justify-between p-1"
            >
              <span>{v.value}</span>
              <span>{v.readonly ? "必填" : ""}</span>
            </div>)}
        <CustomHandle count={1} type="source" position={Position.Right} style={{ top: 74 }} id="inputEnd" />
      </Card>
      <Modal
        title={<span>{data.title as string || '开始'}</span>}
        footer
        open={isModalOpen}
        destroyOnClose={true}
        onCancel={() => {
          setNodes((nodes: Node[]) => {
            const node = nodes.find(node => node.id == id)
            node.data.variable = variable
            return [...nodes];
          })
          setIsModalOpen(false)
        }}
        wrapClassName="clickthrough-modal"
      >
        <VariableConfig value={variable} onChange={setVariable} />
      </Modal>
    </NodeOperation>
  );
}

export default memo(InputNode);
